from openai import OpenAI
from src.utils.get_project_root import get_project_root
import json
from pathlib import Path
from src.utils.logger import get_logger


class Healer:
    def __init__(self, page_name, page_dom_data):
        self.client = OpenAI(
            # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
            api_key='sk-8dcd9ec46bbe42f3947c71d27a21774d',
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )
        self.page_name = page_name
        self.system_prompt_file = get_project_root() / "config" / "prompt_data" / f"{self.page_name}_system_prompt.md"
        if Path.exists(self.system_prompt_file):
            self.system_prompt = self.system_prompt_file.read_text(encoding='utf-8')
        else:
            logger = get_logger()
            logger.error(f'未找到系统提示文件：{self.system_prompt_file}')
            self.system_prompt = ''
        self.tools = []
        self.add_tools()
        self.page_dom_data = page_dom_data

    def call_model(self):
        completion = self.client.chat.completions.create(
            model="qwen3-coder-plus-2025-07-22",
            # Model list: https://help.aliyun.com/zh/model-studio/getting-started/models
            messages=[
                {'role': 'system', 'content': "You are a helpful assistant."},  # Fixed missing closing brace
                {'role': 'user',
                 'content': f'{self.system_prompt},page_name:{self.page_name},page_dom_data:{self.page_dom_data}'}
            ],
            tool_choice={"type": "function", "function": {"name": "write_to_file"}},
            tools=self.tools,
        )
        response = completion.model_dump()
        print(f'模型原始结果：{response}')
        model_response_content = None

        if 'choices' in response and len(response['choices']) > 0:
            first_choice = response['choices'][0]
            if 'message' in first_choice and 'content' in first_choice['message']:
                model_response_content = first_choice['message']

        # 打印模型生成的内容
        if model_response_content is not None:
            print("=" * 50)
            print("模型返回的结果：")
            print(model_response_content)
        else:
            print("未找到模型返回的内容。")

        if model_response_content.get('tool_calls'):
            for tool_call in model_response_content['tool_calls']:
                function_name = tool_call['function']['name']
                arguments = json.loads(tool_call['function']['arguments'])

                if function_name == "write_to_file":
                    # 调用工具函数

                    result = write_to_file(arguments['filename'], arguments['content'], arguments['page_name'])

                    # print(f"Tool call result: {result}")
                    self.client.close()
                    return result

    def add_tools(self):
        # Step 1: 定义 tools（函数描述）
        tools = [
            {
                "type": "function",
                "function": {
                    "name": "write_to_file",
                    "description": "将给定的内容写入指定的文件。",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "filename": {
                                "type": "string",
                                "description": "要写入的文件名",
                            },
                            "content": {
                                "type": "string",
                                "description": "要写入文件的内容"
                            },
                            "page_name": {
                                "type": "string",
                                "description": "页面名称"
                            }
                        },
                        "required": ["filename", "content", "page_name"],
                    },
                }
            }
        ]
        self.tools.append(tools[0])

    @staticmethod
    def get_agent_locator(locator_file_path) -> list:
        with open(locator_file_path, 'r', encoding='utf-8') as f:
            content = json.load(f)
            locator = []
            for k, v in content.items():
                if isinstance(v, dict):
                    locator.append({k: v.get("selector")})
            return locator


def write_to_file(filename: str, content: str, page_name: str):
    """将给定的内容写入指定的文件"""
    proj_root = get_project_root()
    file_path = proj_root / 'config' / "page_element_by_agent" / f"{filename}"
    if not file_path.parent.exists():
        file_path.parent.mkdir(parents=True)
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        return file_path
    except Exception as e:
        print(e)
        return file_path

